<template>
  <a-form ref="form" :model="formData" layout="vertical">
    <div class="form__box">
      <a-form-item :label="`数据绑定key`" field="dataIndex">
        <template v-if="dataObj.mode === 'dataView'">
          <a-select
            v-model="formData.dataViewSel"
            allow-clear
            @change="changeDataViewSel"
          >
            <a-option value="手填">手填</a-option>
            <a-option
              v-for="option in dataObj.queryGroupList"
              :key="option.groupId + ' ' + option.queryKey"
              :value="option.groupId + ' ' + option.queryKey"
              :disabled="
                dataObj.pageData.some(
                  (item) =>
                    item.formData.dataIndex ===
                    option.groupId + ' ' + option.queryKey
                )
              "
              :title="
                (option.formName
                  ? `${option.formName}_${option.columnName}`
                  : option.columnName) +
                (option.aggregateId
                  ? `（${option.funColumnAs}的函数条件）`
                  : '')
              "
              >{{
                option.formName
                  ? `${option.formName}_${option.columnName}`
                  : option.columnName
              }}{{
                option.aggregateId ? `（${option.funColumnAs}函数条件）` : ""
              }}</a-option
            >
          </a-select>
          <a-input
            v-model="formData.dataIndex"
            :disabled="formData.dataViewSel !== '手填'"
          ></a-input>
        </template>
        <a-input
          v-else
          v-model="formData.dataIndex"
          :disabled="formData.notMod"
        ></a-input>
        <field-linkage :formData="formData"></field-linkage>
      </a-form-item>
      <a-form-item :label="`字段名称`" field="name">
        <a-input v-model="formData.name"></a-input>
        <a-checkbox v-model="formData.hideTitle">隐藏标题</a-checkbox>
      </a-form-item>
      <a-form-item :label="`控件类型`" field="type">
        <a-select
          v-model="formData.type"
          @change="changeControlTypes($event, formData)"
        >
          <a-option
            :value="item.value"
            v-for="item in typeOptions"
            :key="item.value"
          >
            {{ item.label }}
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item :label="`数据类型`" field="dataType">
        <a-select v-model="formData.dataType">
          <a-option
            :value="item.value"
            v-for="item in dataTypeOptions"
            :key="item.value"
          >
            {{ item.label }}
          </a-option>
          <template v-if="formData.dataSource === 'alone'">
            <a-option
              :value="item.value"
              v-for="item in otherDataTypeOptions"
              :key="item.value"
            >
              {{ item.label }}
            </a-option>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item :label="`单独查看时的弹窗宽度`" field="controlModalWidth">
        <a-input-number
          v-model="formData.controlModalWidth"
          :min="1000"
        ></a-input-number>
      </a-form-item>
      <a-form-item label="" field="columns">
        <a-tabs v-model="formData.dataSource" @change="changeDataSource">
          <a-tab-pane title="列配置（录入）" key="">
            <table-info-config :form-data="formData"></table-info-config>
          </a-tab-pane>
          <a-tab-pane key="alone" title="数据源（只读）">
            <table-info-config :form-data="formData">
              <!--   刷新图标按钮         -->
              <a-tooltip
                slot="extra"
                style="margin-left: 5px"
                content="拉取列配置"
              >
                <icon-download @click="refreshDataSource" />
              </a-tooltip>
            </table-info-config>
            <a-form-item label="查询数据源">
              <a-select
                v-model="formData.dataSourceId"
                @change="queryDataSourceDetails($event)"
                :filter-option="false"
                @search="queryDatasourceList"
                show-search
                allow-clear
              >
                <a-option
                  v-for="item in dataSourceList"
                  :key="item.dataId"
                  :value="item.dataId"
                  :title="item.dataName"
                >
                  {{ item.dataName }}
                </a-option>
              </a-select>
              <!-- <linked-form-query :formData="formData"></linked-form-query>-->
            </a-form-item>
            <a-form-item label="展示字段">
              <a-select
                v-model="formData.dataShowFields"
                multiple
                allow-clear
                @change="changeDataShowFields"
              >
                <a-option
                  v-for="item in dataShowFieldOptions"
                  :key="item.columnAs"
                  :value="item.columnAs"
                >
                  {{ item.columnAs }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="展示字段排序">
              <draggable tag="div" :list="formData.dataShowFields">
                <template #item="{ element }">
                  <li :key="element">
                    <icon-drag-dot-vertical /> {{ element }}
                  </li>
                </template>
              </draggable>
            </a-form-item>
            <!--            <a-form-item label="传值字段">-->
            <!--              <a-select v-model="formData.dataOptionField" allow-clear>-->
            <!--                <a-option v-for="item in dataShowFieldOptions" :key="item.columnAs" :value="item.columnAs">-->
            <!--                  {{ item.columnAs }}-->
            <!--                </a-option>-->
            <!--              </a-select>-->
            <!--            </a-form-item>-->
            <a-tabs>
              <a-tab-pane
                v-for="(groupItem, index) in formData.dataCondition"
                :title="`条件组${index + 1}`"
                :key="
                  groupItem.tableQueryMappingAddDTO?.groupId ||
                  groupItem.groupId
                "
              >
                <a-form-item
                  v-for="item in groupItem.tableQueryGroupAddDTOList"
                  :key="item.groupId + item.columnKey"
                  :label="`条件字段：${item.columnKey}`"
                >
                  <template v-if="!item.between">
                    <a-select
                      v-model="item.dataIndex"
                      allow-clear
                      placeholder="请选择映射字段"
                    >
                      <a-option
                        v-for="option in nameList"
                        :key="option.dataIndex"
                        :value="option.dataIndex"
                        :disabled="
                          formData.dataCondition.some(
                            (e) => e.dataIndex === option.dataIndex
                          )
                        "
                        >{{ option.name }}</a-option
                      >
                    </a-select>
                    <a-input
                      v-model="item.defaultTheValue"
                      placeholder="条件默认传参"
                    ></a-input>
                  </template>
                  <template v-else>
                    <span
                      v-for="(betweenItem, betweenIndex) in item.between"
                      :key="betweenItem.queryKey"
                    >
                      <a-select
                        v-model="betweenItem.dataIndex"
                        allow-clear
                        :placeholder="`请选择 条件${betweenIndex + 1} 映射字段`"
                      >
                        <a-option
                          v-for="option in nameList"
                          :key="option.dataIndex"
                          :value="option.dataIndex"
                          :disabled="
                            formData.dataCondition.some(
                              (e) => e.dataIndex === option.dataIndex
                            )
                          "
                          >{{ option.name }}</a-option
                        >
                      </a-select>
                      <a-input
                        v-model="betweenItem.defaultTheValue"
                        :placeholder="`条件${betweenIndex + 1}默认传参`"
                      ></a-input>
                    </span>
                  </template>
                </a-form-item>
              </a-tab-pane>
            </a-tabs>
          </a-tab-pane>
        </a-tabs>
      </a-form-item>
      <a-form-item :label="`操作属性`">
        <a-checkbox v-model="formData.hide">隐藏</a-checkbox>
        <a-checkbox v-model="formData.disabled">禁用</a-checkbox>
      </a-form-item>
      <a-form-item :label="`校验`" field="required">
        <a-checkbox v-model="formData.required">必填</a-checkbox>
        <validate-key
          v-if="formData.required"
          :form-data="formData"
        ></validate-key>
      </a-form-item>
      <a-form-item :label="`字段说明`" field="explain">
        <a-textarea v-model="formData.explain">必填</a-textarea>
      </a-form-item>
    </div>
  </a-form>
</template>
<script>
import { basicDefaultData, tagColorList, typeOptions } from "./../base/options";
import FieldLinkage from "@/components/Form/base/fieldLinkage.vue";
import TableInfoConfig from "@/components/Form/base/tableInfoConfig.vue";
import ValidateKey from "@/components/Form/base/validateKey.vue";
import _ from "lodash";
import { nanoid } from "nanoid";
import { changeControlTypes } from "@/mixins/methodsMixins";
export const defaultData = () => ({
  ...basicDefaultData(),
  name: "表格",
  placeholder: "",
  type: "table",
  wrapperCol: 24,
  explain: "",
  columns: [],
  statisticsConfig: [], // 表格额外统计项
  backupColumns: [], // 备份
  dataType: "list",
  dataSource: "",
  dataOptionField: "", // 数据源传值字段
  dataCondition: [], // 数据源与当前表字段绑定关系
  dataShowFields: [], // 数据源展示字段
  controlModalWidth: 1000, // 控件宽度
});
export const dataTypeOptions = [
  {
    label: "list",
    value: "list",
  },
];
const otherDataTypeOptions = [
  {
    label: "string",
    value: "string",
  },
  {
    label: "long",
    value: "long",
  },
  {
    label: "int",
    value: "int",
  },
  {
    label: "float",
    value: "float",
  },
  {
    label: "double",
    value: "double",
  },
];
export default {
  name: "TableInfo",
  components: { ValidateKey, TableInfoConfig, FieldLinkage },
  inject: ["dataObj"],
  data() {
    return {
      rules: {
        dataIndex: [{ required: true, message: "必填" }],
        name: [{ required: true, message: "必填" }],
      },
      dataSourceList: [], // 数据源列表
      dataShowFieldOptions: [], // 数据源展示字段
      tagColorList,
      typeOptions,
      dataTypeOptions,
      otherDataTypeOptions,
    };
  },
  computed: {
    formData() {
      return this.dataObj.pageData[this.dataObj.selectIndex]?.formData || {};
    },
    nameList() {
      return this.dataObj.pageData
        .filter((item) => item.formData.dataIndex && item.formData.name)
        .map((item) => {
          return {
            name: item.formData.name,
            dataIndex: item.formData.dataIndex,
          };
        });
    },
  },
  watch: {
    formData: {
      immediate: true,
      handler(newVal) {
        if (newVal.name === undefined) {
          // console.log(this.dataObj.selectIndex)
          this.dataObj.pageData[this.dataObj.selectIndex].formData =
            defaultData();
          console.log(
            "table",
            this.dataObj.pageData[this.dataObj.selectIndex].formData
          );
        }
      },
    },
  },
  methods: {
    changeDataShowFields(list) {
      const { dataSourceId } = this.formData;
      const oldData = _.cloneDeep(
        this.formData.columns.filter(
          (column) =>
            !(
              column.controlType === "sourceKey" ||
              column.dataId === dataSourceId
            )
        )
      );
      const newData = list.map((columnAs) => {
        const { columnKey, columnType, typeFormat } =
          this.dataShowFieldOptions?.find(
            (item) => item.columnAs === columnAs
          ) || {};
        return {
          cid: nanoid(10),
          title: columnAs,
          dataIndex: columnAs,
          controlType: "sourceKey",
          dataType: columnType,
          typeFormat,
          columnKey: columnKey,
        };
      });

      // 创建一个Map来存储新数据的索引以便快速查找
      const newDataMap = new Map(newData.map((item) => [item.dataIndex, item]));

      // 更新或添加新列
      const updatedColumns = this.formData.columns
        .map((column) => {
          if (newDataMap.has(column.dataIndex)) {
            const newColumn = newDataMap.get(column.dataIndex);
            // 如果旧列的title与新列的title不同，则保留旧列的title
            if (column.title !== newColumn.title) {
              newColumn.title = column.title;
            }
            return { ...column, ...newColumn };
          } else if (
            column.controlType === "sourceKey" &&
            column.dataId === dataSourceId
          ) {
            return column;
          }
          return null; // 标记为删除
        })
        .filter((column) => column !== null);

      // 添加新列
      newData.forEach((newColumn) => {
        if (
          !updatedColumns.some(
            (column) => column.dataIndex === newColumn.dataIndex
          )
        ) {
          updatedColumns.push(newColumn);
        }
      });

      this.formData.columns = updatedColumns.concat(oldData);
    },
    refreshDataSource() {
      this.formData.columns = this.formData.backupColumns;
    },
    changeDataSource(e) {
      console.log(e);
      if (e === "alone") {
        const columns = this.formData.columns;
        // 备份
        this.formData.backupColumns = _.cloneDeep(columns);
        console.log(
          this.dataShowFieldOptions,
          this.formData.dataShowFields,
          this.dataObj.pageData[this.dataObj.selectIndex]?.formData,
          "展示字段"
        );
        this.formData.columns =
          this.formData.dataShowFields?.map((columnAs) => {
            const { columnKey, columnType, typeFormat } =
              this.dataShowFieldOptions?.find(
                (item) => item.columnAs === columnAs
              ) || {};
            return {
              cid: nanoid(10),
              title: columnAs,
              dataIndex: columnAs,
              controlType: "sourceKey",
              dataType: columnType,
              typeFormat,
              columnKey: columnKey,
            };
          }) || [];
        this.dataObj.pageData[this.dataObj.selectIndex].isSendData = true;
      } else {
        this.formData.backupColumns &&
          (this.formData.columns = _.cloneDeep(this.formData.backupColumns));
        this.dataObj.pageData[this.dataObj.selectIndex].isSendData = true;
        this.formData.dataType = "list";
      }
    },
    // 选择了数据源，需要查询有哪些展示字段
    async queryDataSourceDetails(dataId, id, dataShowFields) {
      try {
        if (!dataId) {
          this.formData.dataCondition = [];
          return;
        }
        this.formData.dataOptionField = id || null;
        this.formData.dataShowFields = dataShowFields || [];
        const result = await this.$http.get(
          "/datasource/queryDataSourceDetail",
          {
            params: {
              dataId,
            },
          }
        );
        const { data } = result;
        const { dataColumnQueryDTOList, aggregateFunctionInfoReqDTO } = data;
        const { aggregateFunctionInfoAddDTOList } =
          aggregateFunctionInfoReqDTO || {};
        const mergedList = dataColumnQueryDTOList.concat(
          aggregateFunctionInfoAddDTOList || []
        );
        // 需要根据columnKey去重后的对象数组，而不是单纯的columnKey集合，可以进一步处理：
        this.dataShowFieldOptions = mergedList.filter((item, index, self) => {
          return index === self.findIndex((t) => t.columnAs === item.columnAs);
        });
        _.assign(this.formData, {
          dataCondition: data.queryGroupReqDTOList?.map((item) => {
            let oldData = {};
            if (id) {
              // 编辑时，先查找原先的值,旧模式
              oldData = this.formData.dataCondition?.find(
                (e) =>
                  e.groupId === item.tableQueryMappingAddDTO.groupId &&
                  e.columnKey === item.tableQueryMappingAddDTO.columnKey
              );
            }
            item.tableQueryGroupAddDTOList.forEach((queryItem) => {
              if (!_.isEmpty(oldData) && !queryItem.between) {
                queryItem.dataIndex = oldData?.dataIndex || null;
                queryItem.defaultTheValue = oldData?.defaultTheValue || null;
              } else {
                const oldV2Data = this.findMatchingQuery(
                  this.formData.dataCondition,
                  queryItem.groupId,
                  queryItem.queryKey
                );
                if (
                  _.isArray(queryItem.between) &&
                  queryItem.between.length &&
                  oldV2Data?.between
                ) {
                  queryItem.between[0] = oldV2Data?.between?.[0];
                  queryItem.between[1] = oldV2Data?.between?.[1];
                } else if (!_.isArray(queryItem.between)) {
                  queryItem.defaultTheValue =
                    oldV2Data?.defaultTheValue || null;
                  queryItem.dataIndex = oldV2Data?.dataIndex || null;
                }
              }
            });
            return _.cloneDeep(item);
          }),
        });
      } catch (e) {
        console.error("请求失败", e);
      }
    },
    findMatchingQuery(dataCondition, groupId, queryKey) {
      for (const condition of dataCondition) {
        const group = condition.tableQueryGroupAddDTOList;
        if (group) {
          for (const item of group) {
            // 查找具有指定 groupId 和 queryKey 的对象
            if (item.groupId === groupId && item.queryKey === queryKey) {
              return item;
            }
          }
        }
      }

      return null; // 如果没有找到匹配项，则返回 null
    },
    // 查询数据源列表
    async queryDatasourceList(dataName) {
      // try {
      //   const result = await this.$http.post(`/datasource/querySourceAllList`, {
      //     dataTypeList: ["select", "selTable", "interface"],
      //     dataName: dataName || "",
      //   });
      //   const { data } = result;
      //   this.dataSourceList = data;
      // } catch (e) {
      //   console.error("请求失败", e);
      // }
    },
    changeDataViewSel(value) {
      if (value === "手填") {
        // 选项内容
        this.formData.dataIndex = "";
      } else {
        this.formData.dataIndex = value;
      }
    },
    changeControlTypes,
  },
  created() {
    this.queryDatasourceList(); // 查询数据源列表
    const { dataSourceId, dataShowFields } = this.formData;
    if (dataSourceId) {
      this.queryDataSourceDetails(dataSourceId, true, dataShowFields);
    }
  },
};
</script>

<style scoped lang="less"></style>
